package com.amigo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.amigo.helper.Constants;
import com.amigo.helper.ImageLoader;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;
import com.amigo.views.RoundImageView;
import com.facebook.Session;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

public class Dashboard extends FragmentActivity {

	private ScrollView navList;
	private DrawerLayout drawer;
	private String str, DB_UserToken;
	private Bitmap bmp;
	private static List<Bitmap> list_images;

	private String searchquery;

	private MyPagerAdapter adapter;
	private ViewPager pager;

	private int num_prev_objects;

	private Boolean Success = false, Success_add = false;
	private String Message, Message_add;

	private String DB_SearchResults;
	private String url_search = Constants.base_url + "search";
	private String url_addfriend = Constants.base_url + "sendFriendRequest";
	private String url_deletefriend = Constants.base_url + "ignoreUser";
	private String url_deduct_credits = Constants.base_url + "updateCredits";

	private JSONArray SearchResults;
	private ProgressDialog ringProgressDialog = null;

	private EditText search;
	private RoundImageView profile_image;

	private String ID_to,ID_block, Credits_Remaining;

	public ImageLoader imageLoader;

	private int Credits;
//	private boolean Success_credits = false;
	boolean shownoresults;
	
	private InterstitialAd interstitial;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_dashboard);
		DB_UserToken = JsonFileUtility.ReadJsonData(Constants.TAG_UserGUID);
		str = JsonFileUtility.ReadJsonData(Constants.TAG_UserObject);
		profile_image = (RoundImageView) findViewById(R.id.profile_image);
		search = (EditText) findViewById(R.id.Search);
		
		
	    // Google AdMob
	    // Create the interstitial.
	    interstitial = new InterstitialAd(this);
	    interstitial.setAdUnitId("ca-app-pub-7358427586744734/7528367603");

	    // Create ad request.
	    AdRequest adRequest = new AdRequest.Builder()
	    
	    //Add Test device
	    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("AE95886E0D5F43F149D7A7505A9D5432") //Comment these two lines later to display real ads
               .build();

	    // Begin loading your interstitial.
	    interstitial.loadAd(adRequest);
	    
	    interstitial.setAdListener(new AdListener() {
	        @Override
	        public void onAdClosed() {
	          AdRequest adRequest = new AdRequest.Builder()
	          .addTestDevice("AE95886E0D5F43F149D7A7505A9D5432")
	          .build();
	          interstitial.loadAd(adRequest);
	        }
	    });
	    
	    
		list_images = new ArrayList<Bitmap>();

		ringProgressDialog = new ProgressDialog(this);
		ringProgressDialog.setIndeterminate(true);
		ringProgressDialog.setCancelable(false);
		ringProgressDialog.setTitle("Searching");
		ringProgressDialog.setMessage("Finding Amigos");

		new GetuserProfilePicTask().execute();
		drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		navList = (ScrollView) findViewById(R.id.drawer);
		imageLoader = new ImageLoader(getApplicationContext());
		// Pager Settings and code
		pager = (ViewPager) findViewById(R.id.pager);

		Intent fromgoogle = getIntent();

		if (fromgoogle.hasExtra("FromGoogle")) {
			if (fromgoogle.getBooleanExtra("FromGoogle", false))
				JsonFileUtility.CreateAndSaveFile("Logout_GPLUS", "false");
		}

		search.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				boolean handled = false;
				if (actionId == EditorInfo.IME_ACTION_GO) {
					InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

					inputManager.hideSoftInputFromWindow(getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);

					num_prev_objects = list_images.size();
					searchquery = search.getText().toString();
					new SearchTask().execute();
					handled = true;
				}
				return handled;
			}
		});

		ImageView search_icon = (ImageView) findViewById(R.id.search_icon);
		search_icon.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

				inputManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

				num_prev_objects = list_images.size();
				searchquery = search.getText().toString();
				new SearchTask().execute();

			}
		});

		adapter = new MyPagerAdapter();

		searchquery = "";
		new SearchTask().execute();

	}
	
	public void displayInterstitial() {
	    if (interstitial.isLoaded()) {
	      interstitial.show();
	    }
	  }

	public void notifications(View v) {
		startActivity(new Intent(this, Notifications.class));
		finish();
	}

	public void sendreq(View view) {
		int i = pager.getCurrentItem();

		JSONObject jsonObj;
		try {
			JSONArray jsonarray = new JSONArray(DB_SearchResults);
			jsonObj = jsonarray.getJSONObject(i);
			ID_to = jsonObj.getString("id");
			Log.d("Cuurent id ", ID_to);

		} catch (JSONException e) {
			
			e.printStackTrace();
		}

		new AddFriendTask().execute();
	}

	public void delreq(View view) {

		int i = pager.getCurrentItem();
		
		 JSONObject jsonObj;
		 try {
		 JSONArray jsonarray = new JSONArray(DB_SearchResults);
		 jsonObj = jsonarray.getJSONObject(i);
		 ID_block = jsonObj.getString("id");
		 Log.d("Cuurent id " , ID_block);
		
		 } catch (JSONException e) {
		 // TODO Auto-generated catch block
		 e.printStackTrace();
		 }
		
		 new DeleteFriendTask().execute();

	}

	public void skipreq(View view) {
		
		
		displayInterstitial();
		
		Log.d("list size", "" + list_images.size());
		if (list_images.size() >= 1) {

			JSONArray jsonarray;

			int i = pager.getCurrentItem();

			pager.setCurrentItem(i + 1, true);
			list_images.remove(i);
			adapter.notifyDataSetChanged();
			
			pager.setCurrentItem(i, true);
			pager.setAdapter(adapter);

			try {
				jsonarray = new JSONArray(DB_SearchResults);
				JSONArray jsonarray_new = new JSONArray();
				for (int in = 0; in < jsonarray.length(); in++) {
					if (in != i) {
						jsonarray_new.put(jsonarray.getJSONObject(in));
					}
				}
				DB_SearchResults = jsonarray_new.toString();
				JsonFileUtility.CreateAndSaveFile(Constants.TAG_SearchResults,
						DB_SearchResults);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		if (list_images.size() == 0) {

			searchquery = "";
			new SearchTask().execute();
		}
	}

	public void Logout(View view) {

		if (Session.getActiveSession() != null
				&& Session.getActiveSession().isOpened()) {
			Session.getActiveSession().closeAndClearTokenInformation();
		}
		JsonFileUtility.CreateAndSaveFile("Logout_GPLUS", "true");
		JsonFileUtility.DeleteJsonData(Constants.TAG_UserGUID);
		JsonFileUtility.DeleteJsonData(Constants.TAG_UserObject);
		startActivity(new Intent(Dashboard.this, Login.class));
		finish();

	}

	public void ProfileEdit(View view) {

		// startActivity(new Intent(Dashboard.this, UserProfile.class));
		// finish();
	}

	public void AmigosList(View view) {

		startActivity(new Intent(Dashboard.this, Amigos.class));
		finish();

	}

	public void Myaccount(View view) {
		Toast.makeText(getApplicationContext(),
				"This will send you to myaccount screen", Toast.LENGTH_SHORT)
				.show();

	}

	public void Info(View view) {
		startActivity(new Intent(Dashboard.this, About.class));
		finish();

	}

	public void HelpandSupport(View view) {
		startActivity(new Intent(Dashboard.this, Help.class));
		finish();

	}

	public void Settings(View view) {
		startActivity(new Intent (this , Settings.class));
		finish();
	}

	public void onOpenLeftDrawer(View view) {
		drawer.openDrawer(navList);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ringProgressDialog.dismiss();

	}

	private class MyPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return list_images.size();
		}

		/**
		 * Create the page for the given position. The adapter is responsible
		 * for adding the view to the container given here, although it only
		 * must ensure this is done by the time it returns from
		 * {@link #finishUpdate()}.
		 * 
		 * @param container
		 *            The containing View in which the page will be shown.
		 * @param position
		 *            The page position to be instantiated.
		 * @return Returns an Object representing the new page. This does not
		 *         need to be a View, but can be some other container of the
		 *         page.
		 */
		@Override
		public Object instantiateItem(View collection, int position) {
			ImageView view = new ImageView(Dashboard.this);
			view.setImageBitmap(list_images.get(position));
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {

					Intent i = new Intent(Dashboard.this, Profile.class);
					i.putExtra("Index", pager.getCurrentItem());
					Log.d("new actvity started", "Started");
					startActivity(i);
					finish();

				}
			});
			((ViewPager) collection).addView(view, 0);

			return view;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((ImageView) object);
		}

		/**
		 * Remove a page for the given position. The adapter is responsible for
		 * removing the view from its container, although it only must ensure
		 * this is done by the time it returns from {@link #finishUpdate()}.
		 * 
		 * @param container
		 *            The containing View from which the page will be removed.
		 * @param position
		 *            The page position to be removed.
		 * @param object
		 *            The same object that was returned by
		 *            {@link #instantiateItem(View, int)}.
		 */
		@Override
		public void destroyItem(View collection, int position, Object view) {
			((ViewPager) collection).removeView((ImageView) view);
		}

		/**
		 * Called when the a change in the shown pages has been completed. At
		 * this point you must ensure that all of the pages have actually been
		 * added or removed from the container as appropriate.
		 * 
		 * @param container
		 *            The containing View which is displaying this adapter's
		 *            page views.
		 */
		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

	}

	@Override
	public void onBackPressed() {

	}
	
	
	private class DeleteFriendTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... arg) {
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("who", DB_UserToken));
			params.add(new BasicNameValuePair("whom", ID_block));

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_deletefriend,
					ServiceHandler.POST, params);
			Log.d("Response: ", "> " + jsonStr);
			if (jsonStr != null) {
				JSONObject jsonobj;
				try {
					jsonobj = new JSONObject(jsonStr);
					Success_add = jsonobj.getBoolean("success");
					Message_add = jsonobj.getString("message");

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			if (Success_add == true) {
			
				int i = pager.getCurrentItem() ; 
				pager.setCurrentItem(i + 1, true);
				Toast.makeText(getApplicationContext(), Message_add,
						Toast.LENGTH_SHORT).show();
				
				list_images.remove(i);
				adapter.notifyDataSetChanged();
				pager.setAdapter(adapter);
				pager.setCurrentItem(i , true);
			super.onPostExecute(result);
		}
	}
	}

	private class AddFriendTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			Credits = Integer.parseInt(JsonFileUtility
					.ReadJsonData(Constants.Tag_Credits));
			Log.d("Credits", "" + Credits);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			Success_add = false ; 
			if (Credits > 0) {
				ServiceHandler sh = new ServiceHandler();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("requestedBy", DB_UserToken));
				params.add(new BasicNameValuePair("requestedTo", ID_to));

				// Making a request to url and getting response
				String jsonStr = sh.makeServiceCall(url_addfriend,
						ServiceHandler.POST, params);
				Log.d("Response: ", "> " + jsonStr);
				if (jsonStr != null) {
					JSONObject jsonobj;
					try {
						jsonobj = new JSONObject(jsonStr);
						Success_add = jsonobj.getBoolean("success");
						Message_add = jsonobj.getString("message");

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
			else
			{
				Log.d("credits " , "you dont have enough credits");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
if (Credits > 0 )
{
			if (Success_add == true) {
				new DeductCredits().execute();
				int i = pager.getCurrentItem() ; 
				pager.setCurrentItem(i + 1, true);
				Toast.makeText(getApplicationContext(), Message_add,
						Toast.LENGTH_SHORT).show();

				JsonFileUtility.CreateAndSaveFile(Constants.Tag_Credits, ""
						+ Credits);

			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Dashboard.this);
				builder.setTitle("Add Amigo ");
				builder.setMessage(Message_add);
				builder.setNeutralButton("Ok",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});

				AlertDialog alertDialog = builder.create();
				alertDialog.setCancelable(false);

				// show it
				alertDialog.show();
			}
		}
else
{
	AlertDialog.Builder builder = new AlertDialog.Builder(
			Dashboard.this);
	builder.setTitle("Oops ! Looks like you have run out of credits");
	builder.setMessage("You Do Not Have Enough Credits ! \nYou can Buy More Credits in the My Account Section");
	builder.setPositiveButton("Buy More Credits",
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {
					
					//TODO - GOTO My accounts sections and buy credits

				}
			});
	
	builder.setNegativeButton("Cancel",
			new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {
					
					

				}
			});
	

	AlertDialog alertDialog = builder.create();
	alertDialog.setCancelable(false);

	// show it
	alertDialog.show();}
	}

	}

	private class DeductCredits extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Credits = Credits - 1;
			Log.d("Credits on pre execute", "" + Credits);
			

		}

		@Override
		protected Void doInBackground(Void... params) {
			Log.d("do in background", "started");
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("id", DB_UserToken));
			param.add(new BasicNameValuePair("credits", "" + Credits));

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_deduct_credits,
					ServiceHandler.POST, param);
			Log.d("RESPONSE", jsonStr);
//			if (jsonStr != null) {
//
//				try {
//					JSONObject json_credits = new JSONObject(jsonStr);
//					
//						
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//
//			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			JsonFileUtility.CreateAndSaveFile(Constants.Tag_Credits, ""
					+ Credits);
		}

	}

	private class SearchTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			shownoresults = false;
			ringProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name", searchquery));
			params.add(new BasicNameValuePair("currentUser", DB_UserToken));

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url_search,
					ServiceHandler.POST, params);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {

				try {
					Object json = new JSONTokener(jsonStr).nextValue();
					if (json instanceof JSONArray) {
						SearchResults = new JSONArray(jsonStr);
						DB_SearchResults = SearchResults.toString();
						Success = true;

					} else if (json instanceof JSONObject) {
						JSONObject jsonObj = new JSONObject(jsonStr);

						Success = jsonObj.getBoolean("success");
						Message = jsonObj.getString("message");
					}

					if (Success == true) {
						try {
							for (int index = 0; index < SearchResults.length(); index++) {
								JSONObject ResultObj = SearchResults
										.getJSONObject(index);

								// JSONArray profile_images_array =
								// ResultObj.getJSONArray("profile_images");

								if (ResultObj.opt("profile_images") instanceof Boolean) {
									Bitmap temp_bmp = BitmapFactory
											.decodeResource(getResources(),
													R.drawable.default_dp_face);
									list_images.add(temp_bmp);

								} else {

									JSONArray profile_images_array = ResultObj
											.getJSONArray("profile_images");
									JSONObject profile_image_object = profile_images_array
											.getJSONObject(0);
									String temp_url = profile_image_object
											.getString("image_url");
									Bitmap temp_bmp = imageLoader
											.getBitmap(Constants.base_url
													+ temp_url);
									list_images.add(temp_bmp);

								}

							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

					else {

						shownoresults = true;
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			if (shownoresults) {
				showsearchingdialog();
			}

			for (int i = 0; i < num_prev_objects; i++) {

				list_images.remove(0);
				adapter.notifyDataSetChanged();
				pager.refreshDrawableState();

			}

			pager.setAdapter(adapter);

			JsonFileUtility.CreateAndSaveFile(Constants.TAG_SearchResults,
					DB_SearchResults);

			ringProgressDialog.dismiss();
		}

	}

	public class GetuserProfilePicTask extends AsyncTask<Void, Void, Void> {
		String image_url = "init";

		@Override
		protected Void doInBackground(Void... params) {
			try {
				JSONObject json = new JSONObject(str);
				Credits_Remaining = json.getString("credits");

				if (json.opt("profile_images") instanceof JSONArray) {

					JSONArray profile_images_array = json
							.getJSONArray("profile_images");
					JSONObject profile_image_object = profile_images_array
							.getJSONObject(0);
					image_url = profile_image_object.getString("image_url");
				}

				Log.d("Image_Url", image_url);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			imageLoader.DisplayImage(Constants.base_url + image_url,
					profile_image);
			JsonFileUtility.CreateAndSaveFile(Constants.Tag_Credits,
					Credits_Remaining);
		}

	}

	private void showsearchingdialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Dashboard.this);
		builder.setTitle(Message);
		builder.setMessage("Please try a different keyword . Make sure you spell it correctly.");
		builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				searchquery = "";
				num_prev_objects = 0;
				search.setText("");
				new SearchTask().execute();
			}
		});

		AlertDialog alertDialog = builder.create();

		// show it
		alertDialog.show();

	}

}
